package com.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.constant.MessageConstant;
import com.exception.CustomException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mapper.UserMapper;
import com.pageResult.PageResult;
import com.pojo.User;
import com.query.QueryPageBean;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass=UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();

    @Override
    public User queryByUserNameAndRoleAndMenu(String name) {
        return userMapper.queryByUserNameAndRoleAndMenu(name);
    }

    @Override
    public PageResult selectByQueryString(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize(),true);
        Page<User> page = userMapper.selectByQueryString(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    @Transactional
    public void delete(Integer id) throws CustomException {
        Integer count = userMapper.queryByUserId(id);
        if(count>0){//如果该用户有角色在引用则抛出异常
            throw new CustomException(MessageConstant.USER_IN_USE);
        }
        //否则删除
        userMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public void add(User user, Integer[] RoleIds) {
        //添加时候密码加密一下
        user.setPassword(encoder.encode(user.getPassword()));
        //先添加用户数据
        userMapper.insertSelective(user);
        //在添加用户和角色第三方表数据
        if(RoleIds!=null && RoleIds.length>0){//不为空的情况下
            userMapper.addUserAndRole(user.getId(),RoleIds);
        }
    }

    @Override
    public User queryById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer[] queryByRoleId(Integer RoleId) {
        return userMapper.queryByRoleId(RoleId);
    }

    @Override
    @Transactional
    public void update(User user, Integer[] RoleIds) {
        //修改时候密码加密一下
        user.setPassword(encoder.encode(user.getPassword()));
        //先修改用户数据
        userMapper.updateByPrimaryKeySelective(user);
        if(RoleIds!=null && RoleIds.length>0){//不为空的情况下
            //1.先删除在重新添加
            userMapper.deleteByUser(user.getId());
            //添加
            userMapper.addUserAndRole(user.getId(),RoleIds);
        }else {
            userMapper.deleteByUser(user.getId());
        }

    }

    @Override
    public List<User> queryAll() {
        return userMapper.selectByExample(null);
    }
}
